import { useState, useEffect, useImperativeHandle, forwardRef } from "react";
import { Radio, Form, Select, message, Button, Checkbox } from "antd";
import type { optionType, questionType, controlLogicType } from "@/types/index";
import { modalState } from "@/stores/modalState";
import { ConcernSelectContent } from "../stye";

interface concernType {
  value: string;
  id: number;
  option: optionType[];
}
export default forwardRef(function ConcernSelect({ childId = 0, showAdd = true, optionId }: { childId: number; optionId?: number; showAdd?: boolean }, ref) {
  const [concernData, setConcern] = useState<concernType[]>([{ value: "", id: 0, option: [] }]);
  const [conditionValue, setCondition] = useState<"and" | "or">("and");
  const [questions, setQuestions] = useState<questionType[]>([]);
  const [form] = Form.useForm();

  useEffect(() => {
    if (childId !== 0) {
      const controlLogic = modalState.controlLogic;
      setQuestions(modalState.questions);
      if (controlLogic) {
        setCondition(controlLogic.condition);
        const questionIds = controlLogic.questionIds.split(",").map(item => Number(item));
        const parentAnswer = controlLogic.parentAnswer.split("|").map((item: string) => item.split(",").map(id => Number(id)));
        const option: Record<string, number[]> = {};
        const concernList: concernType[] = modalState.questions.flatMap(item => (questionIds.indexOf(item.id) !== -1 ? { value: item.title, id: item.id, option: item.option } : []));
        for (let i in questionIds) {
          option[questionIds[i]] = parentAnswer[i];
        }
        setConcern(concernList);
        form.setFieldsValue(option);
      }
    }
  }, [childId, form]);

  //选择数据
  const changeSelect = (value: number, index: number) => {
    if (concernData[index].id === value) return;
    const ids = concernData.map(item => item.id).indexOf(value);
    if (ids !== -1) {
      concernData[index].value = questions.find(item => item.id == concernData[index].id)?.title || "";
      return message.info("关联题目不能重复");
    }
    let data = questions.find(item => item.id == value);
    const id = concernData[index].id;
    concernData[index].value = data?.title || "";
    concernData[index].id = value;
    concernData[index].option = data?.option || [];
    setConcern([...concernData]);
    form.resetFields([id]);
  };
  //反选
  const invert = (index: number, id: number) => {
    const option = form.getFieldValue(id) || [];
    const optionList = concernData[index].option.map(item => item.id);
    const newOption = optionList.filter(item => !option.includes(item));
    form.setFieldValue(id, newOption);
  };
  //新增
  const frontAdd = () => {
    if (concernData.length == questions.length) return message.info("已超过可关联题目数量！");
    setConcern([...concernData, { value: "", id: concernData.length + 1, option: [] }]);
  };
  //取消
  const frontCancel = (index: number, id: number) => {
    concernData.splice(index, 1);
    setConcern([...concernData]);
    form.resetFields([id]);
  };

  // 删除关联
  const deleteAll = () => {
    form.resetFields();
    setConcern([{ value: "", id: 0, option: [] }]);
  };

  // 子组件暴露方法
  useImperativeHandle(ref, () => ({
    //确定
    getConcern() {
      let ids: string[] = [];
      let parentAnswer = [];
      let formObj = form.getFieldsValue();
      console.log("from", formObj);

      for (let i in formObj) {
        if (formObj[i].length) {
          ids.push(i);
          parentAnswer.push(formObj[i].join(","));
        }
      }
      const controlLogic: controlLogicType = {
        questionIds: ids.join(),
        childId: childId,
        parentAnswer: parentAnswer.join("|"),
        condition: conditionValue
      };
      if (optionId !== undefined) controlLogic.optionId = optionId;
      return controlLogic;
    }
  }));

  return (
    <ConcernSelectContent>
      <Form layout="vertical" className="front-list" form={form}>
        {concernData.map((item, index) => {
          return (
            <div className="front-item" key={item.id}>
              <div className="front-title flex align-items">
                <div className="front-text">关联题目{concernData.length > 1 && <span>{index + 1}</span>} :</div>
                <div className="front-search flex-between align-items">
                  <Select
                    options={questions}
                    value={item.value}
                    fieldNames={{ label: "title", value: "id" }}
                    style={{ width: "90%" }}
                    filterOption={(input, option) => (option?.title ?? "").toLowerCase().includes(input.toLowerCase())}
                    onChange={value => changeSelect(Number(value), index)}
                  />
                  {showAdd && (index === 0 ? <span onClick={frontAdd}>+更多</span> : <span onClick={() => frontCancel(index, item.id)}>-取消</span>)}
                </div>
              </div>
              {item.option.length > 0 && (
                <div className="front-option">
                  <div className="front-tip">
                    <p>当“关联题目{index + 1}”选择下面的选项：</p>
                    <Button size="small" onClick={() => invert(index, item.id)}>
                      反选
                    </Button>
                  </div>
                  <Form.Item name={item.id}>
                    <Checkbox.Group>
                      {item.option.map(subItem => (
                        <Checkbox className="flex front-checkbox" key={subItem.id} value={subItem.id}>
                          {subItem.content}
                        </Checkbox>
                      ))}
                    </Checkbox.Group>
                  </Form.Item>
                </div>
              )}
            </div>
          );
        })}
      </Form>
      {concernData.length > 1 && (
        <div className="front-radio">
          <div className="front-title flex">
            <div className="front-text">关联多题时：</div>
            <span>多题（每个矩阵行标题视为一题）间</span>
          </div>
          <div className="front-option">
            <Radio.Group value={conditionValue} onChange={e => setCondition(e.target.value)}>
              <Radio value="and">为“且”的关系</Radio>
              <Radio value="or">为“或”的关系</Radio>
            </Radio.Group>
          </div>
        </div>
      )}
      {showAdd && ((concernData[0] && concernData[0].option.length) || concernData.length > 1) && (
        <Button type="primary" danger style={{ marginTop: 20 }} onClick={deleteAll}>
          删除所有关联
        </Button>
      )}
    </ConcernSelectContent>
  );
});
